import {
  cartRemove,
  cartUpdatenum,
  cartUpdateSelectone,
  cartGetRecommendlist,
} from '@/api/cart'

import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { Dialog } from 'vant'



export function useCartList(user: any, cartStore: any) {
  // 购物车商品列表
  const { cartList } = storeToRefs(cartStore)
  const isLoading = ref(true)
  // 使用name绑定元素的cartid
  const handleChangeGoodNum = (
    value: number,
    { name }: { name: string;[propName: string]: any }
  ) => {
    cartUpdatenum({
      cartid: name,
      num: value,
    }).then((res: any) => {
      if (res.code === '200') {
        console.log('change', value)
        // 如果想要异步执行，在确认后端更新数据后前端展示数据变化可以使用下面的代码，
        // 但需要注意，value的变化会再次导致函数的执行，可以在上层做一次value是否相等的判断，以减少重复请求
        // this.cartList.find((item) => item.cartid === name).num = value;
      }
    })
  }
  const handleDeleteGood = (cartid: string) => {
    // 使用异步关闭，在关闭之前，删除元素
    Dialog.confirm({
      message: '确认删除？',
      beforeClose: (action, done) => {
        if (action === 'confirm') {
          cartRemove({
            cartid,
          })
            .then((res: any) => {
              if (res.code === '200') {
                // 后端删除成功后前端数据对应展示，减少一次数据刷新请求
                cartList.value.splice(
                  cartList.value.findIndex((item) => item.cartid === cartid),
                  1
                )
                done()
              }
            })
            .catch((err) => console.error(err))
        } else {
          done()
        }
      },
    })
  }
  // click可以避免二次触发，这里需要注意
  const handleSelectOne = (cartid: string, flag: boolean) => {
    cartUpdateSelectone({
      cartid,
      flag,
    })
      .then((res) => {
        console.log(res)
      })
      .catch((err) => console.error(err))
  }

  const refresh = async () => {
    await cartStore.getCartListData(user.userid)
    isLoading.value = false
  }
  onMounted(() => {
    cartStore.getCartListData(user.userid)
  })

  return {
    cartList,
    isLoading,
    handleChangeGoodNum,
    handleDeleteGood,
    handleSelectOne,
    refresh
  }
}

export function useRecommendList() {
  const loading = ref(false)
  let recommendlistCount = 1
  const finished = ref(false)
  const recommendList = ref([])
  const getRecommendlist = () => {
    loading.value = true
    cartGetRecommendlist({
      count: recommendlistCount++,
    })
      .then((res: any) => {
        console.log('***', res)
        if (res.code === '200') {
          loading.value = false
          if (res.data.length === 0) {
            finished.value = true
            return false
          }
          recommendList.value = res.data
        }
      })
      .catch((err) => console.error(err))
  }
  onMounted(() => {
    getRecommendlist()
  })
  return {
    loading,
    finished,
    recommendList,
    getRecommendlist
  }
}
